package com.book.bookmanager.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.bookmanager.mapper.menuMapper;
import com.book.bookmanager.pojo.Menu;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class menuServiceImpl extends ServiceImpl<menuMapper, Menu> implements menuService{

    @Override
    public List<Menu> getAllList() {
        //一级菜单
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Menu::getParent_id,0);
        List<Menu> menuList = this.list(wrapper);

        //子菜单
        setMenuChildren(menuList);
        return menuList;
    }

    @Override
    public List<Menu> getMenuListByUserName(String userName) {
        //一级菜单
        List<Menu> menuList = this.baseMapper.getMenuListByUserName(userName, 0);

        //子菜单
        setMenuChildrenByUserName(userName, menuList);
        return menuList;
    }

    private void setMenuChildrenByUserName(String userName, List<Menu> menuList) {
        if(menuList != null){
            for (Menu menu: menuList){
                List<Menu> subMenuList = this.baseMapper.getMenuListByUserName(userName, menu.getMenu_id());

                menu.setChildren(subMenuList);
                //递归查询多级菜单
                setMenuChildrenByUserName(userName,subMenuList);
            }
        }
    }

    private void setMenuChildren(List<Menu> menuList) {
        if (menuList != null) {
            for(Menu menu: menuList){

                LambdaQueryWrapper<Menu> SubWrapper = new LambdaQueryWrapper<>();
                SubWrapper.eq(Menu::getParent_id,menu.getMenu_id());
                List<Menu> subMenuList = this.list(SubWrapper);
                menu.setChildren(subMenuList);

                //递归
                setMenuChildren(subMenuList);
            }
        }
    }
}
